﻿#include "widget.h"
#include "ui_widget.h"
#include <QProcess>
#include <QStandardPaths>
#include <QDateTime>
#include <QDir>
#include <QTextCodec>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QApplication>
#include <QStringList>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{

    ui->setupUi(this);
    initApp();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::installAppFilter()
{
    ui->lineEditSourcePath->installEventFilter(this);
    //ui->lineEditTargetPath->installEventFilter(this);
    ui->lineEditRepeat->installEventFilter(this);
}
void Widget::bindConnect()
{
    connect(this,&Widget::dblMouseButtonSignal,[=](QString arg1){
        QString dir;
       qDebug() << arg1 ;
        if(arg1.toUpper() == "SOURCE")
        {
            dir =  QFileDialog::getOpenFileName(NULL,toL8B("打开文件"),m_OpenPath);
            findOpenFilePath(dir,m_OpenPath);
            ui->lineEditSourcePath->setText(dir);
        }
//        else if(arg1.toUpper() == "TARGET")
//        {
//            dir =  QFileDialog::getExistingDirectory(NULL,toL8B("打开文件夹"),m_OpenPath);
//            findOpenFilePath(dir,m_OpenPath);
//            ui->lineEditTargetPath->setText(dir);
//        }
        else if(arg1.toUpper() == "REPEAT")
        {
            findOpenFilePath(dir,m_OpenPath);
            dir = QFileDialog::getOpenFileName(NULL,toL8B("打开文件"),m_OpenPath);
            m_OpenPath = dir;
            ui->lineEditRepeat->setText(dir);
        }
    });
    connect(m_CreateHtml,&InitCreatHtml::MainPageTestSignal,this,&Widget::on_ShowInitCreateHtmlLog);
    connect(this->ui->textEditLog,&QTextEdit::textChanged,[=](){
       ui->textEditLog->moveCursor(QTextCursor::End);
    });
}
void Widget::findOpenFilePath(QString &src,QString &dest)
{
    int pos = src.lastIndexOf("/",-1);
    dest = src.left(pos);
}
void Widget::initApp()
{
    m_CreateHtml = new InitCreatHtml(this);
    // ###![0]
    ui->toolBox->setCurrentIndex(1);
    m_OpenPath =QString("C:/");
    m_msgID.clear();
    m_AppID.clear();
    m_MAC.clear();
    //暂不需要
    ui->lineEditTargetPath->hide();
    ui->labelTargetPath->hide();

    //###![1]
    getDesktopPath();
    initPage1Placeholder();
    initPage2Placeholder();
    initPage2ComboBox();
    initPage3Placeholder();
    setMyWindIcon();
    bindConnect();
    installAppFilter();
    checkTargetSaveFile();
}
void Widget::setMyWindIcon()
{
    const QPixmap pixmap("://logo.ico");
    QIcon icon(pixmap);
    this->setWindowIcon(icon);
    this->setWindowTitle("View Manager (Ver 0.0.2)");
}
void Widget::initPage2ComboBox()
{
    QStringList list;
    //支持的渠道号
    list << toL8B("自助服务终端") << toL8B("超级柜台");
    ui->comboxChannelType->addItems(list);
    //支持的编辑器
    list.clear();
    QString appStartPath( QApplication::applicationDirPath());
    QString formatMsgPath = QString("%1/%2").arg(appStartPath).arg("formatMsg.ini");
    QSettings setterIni(formatMsgPath, QSettings::IniFormat);
    setterIni.setIniCodec("UTF-8");
    QString ComboBoxIDEList = setterIni.value("ComboBoxIDE/Items").toString();
    QStringList items = ComboBoxIDEList.split("|", QString::SkipEmptyParts);
    for(int i=0; i < items.size(); i++)
    {
       list<< items.at(i).toStdString().data();
    }
    //list<< toL8B("VS Code(只支持默认安装)") << toL8B("Notepad++(UTF-8编码)") ;
    ui->comboBoxEdit->addItems(list);
    //默认使用VS Code++
    SetIDEPath(0);
    //m_OpenOtherEdit = "C:/Program Files/Microsoft VS Code/Code.exe";
    //m_OpenEditOtherName = "Code.exe";

}
void Widget::getDesktopPath()
{
    QString desktop_path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
    QString today = QDateTime::currentDateTime().toString("yyyyMMdd");
    m_tempDir = QString("%1/%2%3").arg(desktop_path).arg("Temp").arg(today);
}
void Widget::initPage1Placeholder()
{
    //page1
    ui->lineEditMsgID->setPlaceholderText(QString(tr("99NISPLC0008")));
    ui->lineEditAppID->setPlaceholderText("E59901");
    ui->lineEditSourcePath->setPlaceholderText("D:/Test/Msg/Msg_B05_finance.xml");
    //ui->lineEditTargetPath->setPlaceholderText("D:/Test/DataPool/Msg_AppID.xml");
    ui->textEditLog->setPlaceholderText(toL8B("日志打印\r\n\r\n源路径和目标路径可以通过鼠标左键双击打开"));
    ui->lineEditName->setPlaceholderText(toL8B("理财签约"));
    ui->lineEditMac->setPlaceholderText("true|false");
}
void Widget::initPage2Placeholder(QString &arg)
{
    //page2
    ui->lineEditP2AppID->setText("");
    ui->lineEditP2AppMsgID->setText("");
    ui->lineEditP2TransName->setText("");
    if("SST" == arg )
    {
        ui->labelMenuID->setText(toL8B("菜单编号(AppID):"));
        ui->labelTranCode->setText(toL8B("交易码(MsgID):"));
        ui->labelTranName->setText(toL8B("交易名称:"));
        ui->lineEditP2AppID->setPlaceholderText("E59901");
        ui->lineEditP2AppMsgID->setPlaceholderText("99NISPLC0008");
        ui->lineEditP2TransName->setPlaceholderText(toL8B("理财签约"));
        ui->buttonTest->show();

    }
    else if("SuperTeller" == arg)
    {
        ui->labelMenuID->setText(toL8B("业务分类(如：理财):"));
        ui->labelTranCode->setText(toL8B("交易码:"));
        ui->labelTranName->setText(toL8B("交易名称:"));

        ui->lineEditP2AppID->setPlaceholderText("B05");
        ui->lineEditP2AppMsgID->setPlaceholderText("99NISPLC0008");
        ui->lineEditP2TransName->setPlaceholderText(toL8B("理财签约"));
        ui->buttonTest->hide();
    }

}
void Widget::initPage3Placeholder()
{
    ui->lineEditRepeat->setPlaceholderText(QString("D:/Test/TransDef_E59901.xml"));
}
void Widget::checkTargetSaveFile()
{
    QString strMsgPath = QString("%1/Msg").arg(m_tempDir);
    QString strDataPoolPath = QString("%1/DataPool").arg(m_tempDir);
    QDir dirMsgPath(strMsgPath);
    if(!dirMsgPath.exists())
    {
        if(!dirMsgPath.mkpath(strMsgPath))
        {
            QMessageBox::critical(this,toL8B("错误"),toL8B("创建%1目录失败").arg(strMsgPath));
            return;
        }
    }
    QDir dirDataPool(strDataPoolPath);
    if(!dirDataPool.exists())
    {
        if(!dirDataPool.mkpath(strDataPoolPath))
        {
            QMessageBox::critical(this,toL8B("错误"),toL8B("创建%1目录失败").arg(strDataPoolPath));
            return;
        }
    }
}
void Widget::ReadMsg(const QString &filePath, const QString &msgID, const QString &AppID)
{
   m_XMLList.clear();
   QFile file(filePath);
   if(!file.exists())
   {
       QMessageBox::critical(this,toL8B("错误"),toL8B("文件%1不存在").arg(filePath));
       return;
   }
   file.encodeName("UTF-8");
   if(!file.open(QIODevice::ReadOnly))
   {
       QMessageBox::critical(this,toL8B("错误"),toL8B("文件打开失败"));
       return;

   }
   //文件关联doc
   QDomDocument doc;
   if(!doc.setContent(&file))
   {
       QMessageBox::critical(this,toL8B("错误"),toL8B("文档 setContent 失败"));
       return;
   }
   file.close();
   //获取根元素
   QDomElement root =doc.documentElement();
   //判断根元素是否有子元素
   if(!root.hasChildNodes())
   {
       return;
   }
   QDomElement firstChild = ParseNode(root, msgID, AppID, 1);
   ParseNode(firstChild,msgID, AppID, 2);
}
QDomElement& Widget::ParseNode(const QDomElement &root,const QString &msgID, const QString &AppID, int arg)
{
    //获取所有的子节点
    QDomElement *targetEmt = new QDomElement;
    QDomNodeList list = root.childNodes();
    for(int i=0; i < list.size();i++)
    {
        targetEmt = &list.at(i).toElement();

        if(msgID == targetEmt->attribute("id") && arg == 1)
        {
            break;
        }
        else if(arg ==2)
        {
            QString targetName = targetEmt->tagName();
            QDomNodeList slist = targetEmt->childNodes();
            for(int k=0; k <slist.count(); k++)
            {
                QDomElement sTargetEmt = slist.at(k).toElement();

                if(sTargetEmt.tagName() == "F_TranCode" && targetName.toUpper() =="REQUEST")
                {
                    m_XMLRoot.m_strFlag ="Request";
                    m_XMLRoot.m_strId = sTargetEmt.tagName();
                    if(sTargetEmt.hasAttribute("Request"))
                    {
                        m_XMLRoot.m_strRequestPath = sTargetEmt.attribute("Request");
                    }

                    m_XMLRoot.m_strValue = sTargetEmt.attribute("value");
                    if(sTargetEmt.hasAttribute("Response"))
                    {
                        m_XMLRoot.m_strResponsePath =sTargetEmt.attribute("Response");
                    }
                    //m_XMLRoot.m_strRemark = sTargetEmt.attribute("remark");
                    if(sTargetEmt.hasAttribute("remark"))
                    {
                        m_XMLRoot.m_strRemark = sTargetEmt.attribute("remark");
                    }
                    else if(sTargetEmt.hasAttribute("remark"))
                    {
                        m_XMLRoot.m_strRemark = sTargetEmt.attribute("Remark");
                    }
                    else
                    {
                        ui->textEditLog->append(toL8B("请检查%1 的 F_TranCode 路径的标签").arg(ui->lineEditMsgID->text()));
                    }
                    m_XMLList.push_back(m_XMLRoot);
                }
                else
                {
                    //Request
                    qDebug() << targetName.toUpper();
                    if(targetName.toUpper() =="REQUEST")
                    {
                        QString reqPath = sTargetEmt.attribute("Request");
                        QStringList reqList = reqPath.split("/",QString::SkipEmptyParts);
                        if(reqList.size() >= 1)
                        {
                            QString resLabel = reqList.at(reqList.count()-1);
                            m_XMLRoot.m_strFlag ="Request";
                            //m_XMLRoot.m_strId = QString("F_%1_%2").arg(AppID).arg(resLabel);
                            m_XMLRoot.m_strId = QString("F_%1").arg(resLabel);
                            m_XMLRoot.m_strRequestPath = reqPath;
                            m_XMLRoot.m_strValue = QString("$%1_P_%2").arg(AppID).arg(resLabel);
                            m_XMLRoot.m_strResponsePath =QString("");
                        }
                    }
                    else if(targetName.toUpper() == "RESPONSE")
                    {
                        //Response
                        QString respPath = sTargetEmt.attribute("Response");
                        QStringList respList =respPath.split("/",QString::SkipEmptyParts);
                        if(respList.size()>=1)
                        {
                            QString respLabel =respList.at(respList.count()-1);
                            m_XMLRoot.m_strFlag ="Response";
                            //m_XMLRoot.m_strId = QString("F_%1_%2").arg(AppID).arg(respLabel);
                            m_XMLRoot.m_strId = QString("F_%1").arg(respLabel);
                            m_XMLRoot.m_strRequestPath = QString("");
                            m_XMLRoot.m_strValue = QString("$%1_RP_%2").arg(AppID).arg(respLabel);
                            m_XMLRoot.m_strResponsePath =respPath;

                        }
                    }
                    else
                    {
                        continue;
                    }
                    if(sTargetEmt.hasAttribute("remark"))
                    {
                        m_XMLRoot.m_strRemark = sTargetEmt.attribute("remark");
                    }
                    else if(sTargetEmt.hasAttribute("Remark"))
                    {
                        m_XMLRoot.m_strRemark = sTargetEmt.attribute("remark");
                    }
                    else
                    {
                        ui->textEditLog->append(toL8B("请检查%1 的 %2 路径的标签").arg(ui->lineEditMsgID->text()).arg(sTargetEmt.attribute("Response")));
                    }
                    m_XMLList.push_back(m_XMLRoot);
                }
            }
        }
    }
    return *targetEmt;
}
void Widget::createXML(QString &filePath)
{
    QFile file(filePath);
    file.encodeName("UTF-8");
    if(!file.open(QIODevice::WriteOnly))
    {
        return;
    }
    QDomDocument doc;
    QDomProcessingInstruction ins;
    ins =doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"utf-8\"");
    doc.appendChild(ins);
    QDomElement root =doc.createElement("Body");
    QDomAttr rAttr = doc.createAttribute("useHEX");
    rAttr.setNodeValue("false");
    root.setAttributeNode(rAttr);
    doc.appendChild(root);
    QTextStream stream(&file);
    doc.save(stream,4);
    file.close();
}
void Widget::appendXML(QString &filePath, XMLFileList &fileList, QString &msgID, QString &msgName,QString &Mac)
{
    QFile file(filePath);
    file.encodeName("UTF-8");
    //先读 ，后写
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,"Err","File Open Fail");
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        //createXML(filePath);
        QMessageBox::critical(this,"Err","doc setContent Fail");
        return;
    }
    file.close();
    //获取根节点
    QDomElement root = doc.documentElement();
    if(root.hasChildNodes())
    {
        qDebug() << "NOT CHILD";
        //追加先判断Msg 是否存在
        QDomNodeList fNodeList = root.childNodes();
        qDebug() << "fNodeList " << fNodeList.count();
        for(int i=0; i < fNodeList.count(); i++)
        {
           QDomElement fEmt = fNodeList.at(i).toElement();
           if(fEmt.attribute("id") == msgID)
           {
               QMessageBox::critical(NULL,toL8B("错误"),toL8B("这个 MsgID: %1 重复").arg(msgID));
               return;
           }

        }
    }

    //不存在子节点
    QDomElement msgEmt = doc.createElement("Msg");
    //插入顺序随机
    QDomAttr msgAttr = doc.createAttribute("id");
    msgAttr.setNodeValue(msgID);
    msgEmt.setAttributeNode(msgAttr);
    msgAttr =doc.createAttribute("mac");
    msgAttr.setNodeValue(Mac);
    msgEmt.setAttributeNode(msgAttr);
    msgAttr =doc.createAttribute("name");
    msgAttr.setNodeValue(msgName);
    msgEmt.setAttributeNode(msgAttr);
    root.appendChild(msgEmt);
    ui->textEditLog->append(toL8B(" 交易码是 id = <font color=\"#FF0000\">%1</font>").arg(msgID));
    ui->textEditLog->append(toL8B("是否校验 mac = <font color=\"#FF0000\">%1</font>").arg(Mac));
    ui->textEditLog->append(toL8B("<font color=\"#000000\">Msg标签\r\n </font>"));
    ui->textEditLog->append(toL8B("<Msg id =\"%1\" name = \"%2\" mac=\"%3\">")
                            .arg(msgID)
                            .arg(msgName)
                            .arg(Mac));
    //一级节点创建成功
    //request节点
    CreateSecondNode(doc,msgEmt,fileList);
    //保存文件
    file.encodeName("UTF-8");
    file.open(QIODevice::WriteOnly);
    QTextStream stream(&file);
    doc.save(stream,4);
    file.close();
}
void Widget::CreateSecondNode(QDomDocument &doc, QDomElement &root,
                              XMLFileList &fileList)
{
    //二级节点
    QDomElement reqRoot = doc.createElement("Request");
    QDomElement respRoot = doc.createElement("Response");
    root.appendChild(reqRoot);
    root.appendChild(respRoot);
    ui->textEditLog->append("<Request>");
    bool reqLog = true;
    bool transcodeFlag = true;
     for(int i=0; i < fileList.count();i++)
     {
         QDomElement childEmt = doc.createElement(fileList.at(i).m_strId);
         QDomAttr childAttr;
         QString requestPath =fileList.at(i).m_strRequestPath;
         QString responsePath = fileList.at(i).m_strResponsePath;
         QStringList reqList = requestPath.split("/",QString::SkipEmptyParts);
         QStringList respList =responsePath.split("/",QString::SkipEmptyParts);
         if(transcodeFlag|| respList.size() == 0 && reqList.at(1).toUpper() == "REQUEST")
         {
             //判读是否为Transcode
            if(transcodeFlag)
            {
                transcodeFlag = false;
                childAttr = doc.createAttribute("Request");

            }
            else
            {
                childAttr = doc.createAttribute(reqList.at(1));
            }
            childAttr.setNodeValue(requestPath);
            childEmt.setAttributeNode(childAttr);
            childAttr =doc.createAttribute("value");
            childAttr.setNodeValue(fileList.at(i).m_strValue);
            childEmt.setAttributeNode(childAttr);
            childAttr =doc.createAttribute("remark");
            childAttr.setNodeValue(fileList.at(i).m_strRemark);
            childEmt.setAttributeNode(childAttr);
            reqRoot.appendChild(childEmt);
            ui->textEditLog->append(toL8B("<%1    Request =\"%2\"   value = \"%3\"  remark = \"%4\" />")
                                    .arg(fileList.at(i).m_strId)
                                    .arg(requestPath)
                                    .arg(fileList.at(i).m_strValue)
                                    .arg(fileList.at(i).m_strRemark));
         }
         else
         {
             if(reqLog)
             {
                 reqLog = false;
                 ui->textEditLog->append("</Request>");
                 ui->textEditLog->append("<Response>");
             }
             childAttr = doc.createAttribute(respList.at(1));
             childAttr.setNodeValue(responsePath);
             childEmt.setAttributeNode(childAttr);
             childAttr =doc.createAttribute("value");
             childAttr.setNodeValue(fileList.at(i).m_strValue);
             childEmt.setAttributeNode(childAttr);
             childAttr =doc.createAttribute("remark");
             childAttr.setNodeValue(fileList.at(i).m_strRemark);
             childEmt.setAttributeNode(childAttr);
             respRoot.appendChild(childEmt);
             ui->textEditLog->append(toL8B("<%1   Response =\"%2\"    value = \"%3\"      remark = \"%4\" />")
                                     .arg(fileList.at(i).m_strId)
                                     .arg(responsePath)
                                     .arg(fileList.at(i).m_strValue)
                                     .arg(fileList.at(i).m_strRemark));
         }
     }
     ui->textEditLog->append("</Response>");
     ui->textEditLog->append("</Msg>");
}


bool Widget::eventFilter(QObject *obj, QEvent *e)
{
   //自定义事件派发
    QMouseEvent *ev = static_cast<QMouseEvent*>(e);
    if(e->type() == QEvent::MouseButtonDblClick && ev->button() == Qt::LeftButton)
    {
        qDebug() << "clicked ";
        if(obj == ui->lineEditSourcePath)
        {
           emit dblMouseButtonSignal("Source");
        }
//        else if(obj == ui->lineEditTargetPath)
//        {
//           emit dblMouseButtonSignal("Target");
//        }
        else if(obj == ui->lineEditRepeat)
        {
           emit dblMouseButtonSignal("Repeat");
        }
        return false;
    }
    return QObject::eventFilter(obj, e);
}

void Widget::on_buttonFile_clicked()
{
    //判断程序是否打开
    //请求报文
    ui->buttonFile->setEnabled(false);
    QString reqFileUrl = QString("%1/request.txt").arg(m_tempDir);
    QFile reqFile(reqFileUrl);
    if(!reqFile.exists())
    {
        //reqFile.remove();
        reqFile.open(QIODevice::WriteOnly);
        reqFile.close();
    }

    //请求报文中文
    QString reqzh_cnFileUrl = QString("%1/requestRemark.txt").arg(m_tempDir);
    QFile reqzh_cnFile(reqzh_cnFileUrl);
    if(!reqzh_cnFile.exists())
    {
        //reqzh_cnFile.remove();
        reqzh_cnFile.open(QIODevice::WriteOnly);
        reqzh_cnFile.close();

    }
    //响应报文
    QString respFileUrl = QString("%1/response.txt").arg(m_tempDir);
    QFile respFile(respFileUrl);
    if(!respFile.exists())
    {
        //respFile.remove();
        respFile.open(QIODevice::WriteOnly);
        respFile.close();
    }

    //中文
    QString respzh_cnFileUrl = QString("%1/responseRemark.txt").arg(m_tempDir);
    QFile respzh_cnFile(respzh_cnFileUrl);
    if(!respzh_cnFile.exists())
    {
        //respzh_cnFile.remove();
        respzh_cnFile.open(QIODevice::WriteOnly);
        respzh_cnFile.close();
    }
    //打开Edit
    QProcess *p = new QProcess(this);
    p->start("tasklist");
    p->waitForFinished();
    qDebug() <<m_OpenOtherEdit << m_OpenEditOtherName;
    //QByteArray res =p->readAllStandardOutput();
    QStringList list;
    list << respzh_cnFileUrl << respFileUrl << reqzh_cnFileUrl << reqFileUrl ;
     p->start(m_OpenOtherEdit,list);
//    if(res.indexOf(m_OpenEditOtherName) == -1)
//    {
//        QStringList list;
//        list << respzh_cnFileUrl << respFileUrl << reqzh_cnFileUrl << reqFileUrl ;
//        p->start(m_OpenOtherEdit,list);
//    }
//    else
//    {
//        QMessageBox::warning(this,toL8B("提示"),toL8B("%1 已在其它实例打开，请先关闭再尝试").arg(m_OpenEditOtherName));
//        ui->buttonFile->setEnabled(true);

//    }
    ui->buttonFile->setEnabled(true);

}
void Widget::ReadFieldAndSaveToData(QString &chanelType)
{
    //读取文件
    m_FieldMap.clear();
    m_FieldGatherList.clear();

    QString AppID =ui->lineEditP2AppID->text().trimmed();
    QString msgID =ui->lineEditP2AppMsgID->text().trimmed();
    QString tranCodeName = ui->lineEditP2TransName->text().trimmed();

    if(AppID.isEmpty()|| msgID.isEmpty() || tranCodeName.isEmpty())
    {
        return;
    }
    QString requestFileUrl = QString("%1/request.txt").arg(m_tempDir);
    QFile file(requestFileUrl);
    file.encodeName("UTF-8");
    ui->textEditLog->append(toL8B("请求报文路径：<font color=\"#00FF00\">%1</font>").arg(requestFileUrl));
    m_resNum =0;
    QStringList resList,resRemarkList;
    QString strLine;
    bool isOk = file.open(QIODevice::ReadOnly);
    if(!isOk)
    {
        QMessageBox::critical(this,toL8B("失败"),toL8B("request.txt 文件 ReadOnly 打开失败"));
        return;
    }
    while (!file.atEnd())
    {
        m_resNum +=1;
        strLine = file.readLine().trimmed();
        strLine =strLine.replace(" ","").replace("<","").replace(">","");
        resList <<strLine;
        ui->textEditLog->append(toL8B("请求报文字段标签：<font color=\"#00FF00\">%1</font>").arg(strLine));

    }
    QString strTotal =toL8B("请求路径总共 <font color=\"#00FF00\">%1</font> 个").arg(m_resNum);
    ui->textEditLog->append(strTotal);
    file.close();
    ui->textEditLog->append("\r\n");
    // 请求报文路径读文件结束

    m_resRemarkNum =0;
    QString reqRemarkFileUrl = QString("%1/requestRemark.txt").arg(m_tempDir);
    QFile resRemarkFile(reqRemarkFileUrl);
    resRemarkFile.encodeName("UTF-8");
    ui->textEditLog->append(toL8B("请求报文域名文件路径：<font color=\"#00FF00\">%1</font>").arg(reqRemarkFileUrl));
    if(!resRemarkFile.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,"Err"," requestRemark.txt File ReadOnly Fail");
        return;
    }

    while (!resRemarkFile.atEnd()) {
        m_resRemarkNum +=1;
        strLine = resRemarkFile.readLine().trimmed();
        resRemarkList << strLine;
        ui->textEditLog->append(toL8B("请求报文域名：<font color=\"#00FF00\">%1</font>").arg(strLine));
    }
    resRemarkFile.close();

    strTotal =toL8B("请求报文域名（Remark） 总数 <font color=\"#00FF00\">%1</font> 个").arg(m_resRemarkNum);
    ui->textEditLog->append(strTotal);

    // 请求报文域名读文件结束

    m_resTagLenMax =0;
    m_TrandataDefLen = 0;
    if(m_resNum == m_resRemarkNum && m_resNum !=0 && m_resRemarkNum !=0)
    {
        // request == remark
        for(int i=0; i < m_resNum; i++)
        {
            m_Field.m_strRequestPath = resList.at(i);
            QStringList list = resList.at(i).split("/");
            QString str = list.at(list.length()-1);
            //QString strTagName = QString("F_%1_%2").arg(AppID).arg(str);
            //两个渠道定义格式一致
            QString strTagName = QString("F_%1").arg(str);
            m_Field.m_strTagName = strTagName;
            //特殊处理
            QString strValue;
            if(QString("SST") == chanelType)
            {
                strValue = QString("%1_P_%2").arg(AppID).arg(str);
            }
            else if(QString("SuperTeller") == chanelType)
            {
                strValue = QString("P_%1_%2").arg(AppID).arg(str);
            }

            m_Field.m_strValue = strValue;
            QString strRemark = resRemarkList.at(i);
            m_Field.m_strRemark = strRemark;
            m_FieldGatherList.push_back(m_Field);
            m_resTagLenMax = compareFour(strValue.length(),strTagName.length(), resList.at(i).length(),m_resTagLenMax);


            QString mapKey;
            if(QString("SST") == chanelType)
            {
                mapKey = QString("%1_P_%2").arg(AppID).arg(str);
            }
            else if(QString("SuperTeller") == chanelType)
            {
                mapKey = QString("P_%1_%2").arg(AppID).arg(str);
            }
            int keyLen =mapKey.length();
            m_TrandataDefLen = compareTwo(keyLen,m_TrandataDefLen);
            m_FieldMap.insert(mapKey,strRemark);
        }
    }

    //response
    QString respFileUrl = QString("%1/response.txt").arg(m_tempDir);
    ui->textEditLog->append(toL8B("响应路径的资源文件路径：<font color=\"#00FF00\">%1</font>").arg(respFileUrl));
    QFile respfile(respFileUrl);
    respfile.encodeName("UTF-8");
    m_respNum =0;
    QStringList respList,respRemarkList;
    if(!respfile.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("response.txt 文件 ReadOnly 打开失败"));
        return;
    }
    while (!respfile.atEnd())
    {
        m_respNum +=1;
        strLine = respfile.readLine().trimmed();
        strLine =strLine.replace(" ","").replace("<","").replace(">","");
        respList <<strLine;
        ui->textEditLog->append(toL8B("响应报文路径字段：<font color=\"#00FF00\">%1</font>").arg(strLine));

    }
    respfile.close();
    strTotal =toL8B("响应路径标签 总数 <font color=\"#00FF00\">%1</font> 个").arg(m_respNum);
    ui->textEditLog->append(strTotal);
    file.close();

    m_respRemarkNum =0;
    QString respRemarkFileUrl = QString("%1/responseRemark.txt").arg(m_tempDir);
    QFile respRemarkFile(respRemarkFileUrl);
    respRemarkFile.encodeName("UTF-8");
    ui->textEditLog->append(toL8B("响应报文域名的资源文件路径：<font color=\"#00FF00\">%1</font>").arg(respRemarkFileUrl));
    if(!respRemarkFile.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("responseRemark.txt 文件 ReadOnly 打开失败"));
        return;
    }
    while (!respRemarkFile.atEnd()) {
        m_respRemarkNum +=1;
        strLine = respRemarkFile.readLine().trimmed();
        respRemarkList << strLine;
        ui->textEditLog->append(toL8B("响应域名字段：<font color=\"#00FF00\">%1</font>").arg(strLine));
    }
    respRemarkFile.close();
    strTotal =toL8B("响应报文域名的标签 总数 <font color=\"#00FF00\">%1</font> 个").arg(m_respRemarkNum);
    ui->textEditLog->append(strTotal);

    m_respTagLenMax = 0;

    if(m_respNum == m_respRemarkNum && m_respNum !=0 && m_respRemarkNum !=0)
    {
        // response == remark
        for(int i=0; i < m_respNum; i++)
        {
            m_Field.m_strResponsePath = respList.at(i);
            QStringList list = respList.at(i).split("/");
            QString str = list.at(list.length()-1);
            //QString strTagName = QString("F_%1_%2").arg(AppID).arg(str);
            QString strTagName = QString("F_%1").arg(str);
            m_Field.m_strTagName = strTagName ;

            QString strValue;
            if(QString("SST") == chanelType)
            {
                strValue = QString("%1_RP_%2").arg(AppID).arg(str);
            }
            else if(QString("SuperTeller") == chanelType)
            {
                strValue = QString("RP_%1_%2").arg(AppID).arg(str);
            }
            m_Field.m_strValue = strValue;
            QString strRemark = respRemarkList.at(i);
            m_Field.m_strRemark = strRemark;
            m_FieldGatherList.push_back(m_Field);
            m_respTagLenMax = compareFour(strValue.length(),strTagName.length(),respList.at(i).length(),m_respTagLenMax);

            QString mapKey;
            if(QString("SST") == chanelType)
            {
                mapKey = QString("%1_RP_%2").arg(AppID).arg(str);
            }
            else if(QString("SuperTeller") == chanelType)
            {
                mapKey = QString("RP_%1_%2").arg(AppID).arg(str);
            }
            int keyLen =mapKey.length();
            m_TrandataDefLen = compareTwo(keyLen,m_TrandataDefLen);
            m_FieldMap.insert(mapKey,strRemark);
        }
    }
}
void Widget::CreateXmlHeadAndBody(QString &targetFile,QString &strXmlHead, QString &findKey)
{
    QFileInfo fileInfo(targetFile);
    qint64 size = fileInfo.size();
    qDebug() << "size  = " << size;
    QFile rFile(targetFile);
    rFile.open(QIODevice::ReadWrite);
    QDomDocument doc;

    if(!doc.setContent(&rFile))
    {
        CreateFileBodyXml(targetFile,strXmlHead);
    }
    rFile.close();
    QDomElement root = doc.documentElement();
    qDebug () << findKey <<root.tagName();
    if(root.isElement() && (root.tagName().compare(findKey,Qt::CaseSensitive) == 0))
    {
        ui->textEditLog->append(toL8B("开始追加标签 重复定义的不追加！"));
        return;
    }
    CreateFileBodyXml(targetFile,strXmlHead);


}
void Widget::CreateFileBodyXml(QString &filePath,QString &strXmlHead )
{

    QFile file(filePath);
    if(!file.open(QIODevice::WriteOnly))
    {
        return;
    }
    QTextStream inStream(&file);
    inStream.setCodec("UTF-8");
    inStream.setGenerateByteOrderMark(true);

//    inStream << QString("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
//    inStream << QString("<Body useHEX=\"false\"> \r\n");
//    inStream << QString("</Body>");
    inStream << strXmlHead;
    file.close();

}
void Widget::DataTransformMsgXML(QString &msgID,QString &tranCodeName,QString &targetFile,QString &chanelType,QString &AppID)
{
    ui->textEditLog->append("xml transform .");
    ui->textEditLog->append(targetFile);
    //判断是否是否需要写入msg xml head
    QString strHead = QString("%1%2%3")
            .arg(QString("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"))
            .arg(QString("<Body useHEX=\"false\"> \r\n"))
            .arg(QString("</Body>"));

    //追加文件
    QString key =QString("Body");

    CreateXmlHeadAndBody(targetFile,strHead,key);
    QString msgLabel;
    MapToPrepareData(msgLabel,chanelType,AppID,msgID,tranCodeName);
    QString keyLabel =QString("</Body>");
    AppendLabel(targetFile, msgLabel, keyLabel);

}
void Widget::MapToPrepareData(QString &msgLabel,QString &chanelType,QString &AppID,QString &msgID, QString &tranCodeName)
{
    QString msgLog;
    QChar space =QChar(' ');
    if(QString("SST") == chanelType)
    {
        msgLabel = QString(4,space).append(QString("<Msg id =\"%1_%2\" mac =\"%3\" name =\"%4\">\r\n").arg(AppID).arg(msgID).arg("true").arg(tranCodeName));
        msgLog = QString(4,space).append(QString("<Msg id =\"%1\" mac =\"%2\" name =\"%3\">").arg(msgID).arg("true").arg(tranCodeName));
    }
    else if(QString("SuperTeller") == chanelType)
    {
        msgLabel = QString(4,space).append(QString("<Msg id =\"%1\" mac =\"%2\" name =\"%3\">\r\n").arg(msgID).arg("true").arg(tranCodeName));
        msgLog = QString(4,space).append(QString("<Msg id =\"%1\" mac =\"%2\" name =\"%3\">").arg(msgID).arg("true").arg(tranCodeName));
    }

    ui->textEditLog->append(msgLog);

    msgLabel += QString(8,space).append("<Request>\r\n");

    msgLog = QString(8,space).append("<Request>");
    ui->textEditLog->append(msgLog);

    m_resTagLenMax = m_resTagLenMax + 4;
    QString strTranCode = QString("F_TranCode");
    QString strRequest = QString("head3");
    QString strRemark = toL8B("交易代码");
    QString strValue = msgID;
    msgLabel +=QString(12,space).append(QString("<%1").arg(strTranCode))
            .append(QString(fillBlankSpace(strTranCode.length(),m_resTagLenMax),space))
            .append("Request=\"%1\"").arg(strRequest)
            .append(QString(fillBlankSpace(strRequest.length(),m_resTagLenMax),space))
            .append(QString(" value=\"%1\"").arg(strValue))
            .append(QString(fillBlankSpace(strValue.length(),m_resTagLenMax-1),space))
            .append(QString("remark =\"%1\"/>\r\n").arg(strRemark));

    msgLog = QString(12,space).append(QString("<%1").arg(strTranCode))
                .append(QString(fillBlankSpace(strTranCode.length(),m_resTagLenMax),space))
                .append("Request=\"%1\"").arg(strRequest)
                .append(QString(fillBlankSpace(strRequest.length(),m_resTagLenMax),space))
                .append(QString(" value=\"%1\"").arg(strValue))
                .append(QString(fillBlankSpace(strValue.length(),m_resTagLenMax),space))
                .append(QString("remark =\"%1\"/>").arg(toL8B("交易代码")));
    ui->textEditLog->append(msgLog);


    for(int m=0; m < m_resNum; m++)
    {
        QString strtarName = m_FieldGatherList.at(m).m_strTagName;
        QString strRequest = m_FieldGatherList.at(m).m_strRequestPath;
        QString strValue = m_FieldGatherList.at(m).m_strValue;
        int tagSpace = fillBlankSpace(strtarName.length(),m_resTagLenMax);
        int reqSpace = fillBlankSpace(strRequest.length(),m_resTagLenMax);
        int valSpace = fillBlankSpace(strValue.length(),m_resTagLenMax);
        msgLabel += QString(12,space)
                .append(QString("<%1").arg(strtarName))\
                .append(QString(tagSpace,space))\
                .append(QString("Request=\"%1\"").arg(strRequest))
                .append(QString(reqSpace,space))\
                .append(QString(" value=\"$%1\"").arg(strValue))\
                .append(QString(valSpace,space))
                .append(QString("remark =\"%1\"/>\r\n").arg(m_FieldGatherList.at(m).m_strRemark));

       msgLog = QString(12,space)
                        .append(QString("<%1").arg(strtarName))\
                        .append(QString(tagSpace,space))\
                        .append(QString("Request=\"%1\"").arg(strRequest))
                        .append(QString(reqSpace,space))\
                        .append(QString(" value=\"$%1\"").arg(strValue))\
                        .append(QString(valSpace,space))
                        .append(QString("remark =\"%1\"/>").arg(m_FieldGatherList.at(m).m_strRemark));

        ui->textEditLog->append(msgLog);

   }
    msgLabel +=QString(8,space).append("</Request>\r\n");

    msgLog = QString(8,space).append("</Request>");
    ui->textEditLog->append(msgLog);

    qDebug() << "Requst end";

    msgLabel +=QString(8,space).append(QString("<Response>\r\n"));

    msgLog =QString(8,space).append("<Response>");
    ui->textEditLog->append(msgLog);

    m_respTagLenMax = m_respTagLenMax + 4;
    int totalNum = m_FieldGatherList.size();
    qDebug() <<QString(" m_resNum =%1 totalNum =%2").arg(m_resNum).arg(totalNum);
    for(int k= m_resNum; k < totalNum; k++)
    {
        QString strTarName = m_FieldGatherList.at(k).m_strTagName;
        QString strResponse = m_FieldGatherList.at(k).m_strResponsePath;
        QString strValue = m_FieldGatherList.at(k).m_strValue;
        msgLabel += QString(12,space)
                .append(QString("<%1").arg(strTarName))\
                .append(QString(fillBlankSpace(strTarName.length(),m_respTagLenMax),space))\
                .append(QString("Response=\"%1\"").arg(strResponse))\
                .append(QString(fillBlankSpace(strResponse.length(),m_respTagLenMax),space))\
                .append(QString(" value=\"$%1\"").arg(strValue))\
                .append(QString(QString(fillBlankSpace(strValue.length(),m_respTagLenMax),space)))
                .append(QString("remark =\"%1\"/>\r\n""").arg(m_FieldGatherList.at(k).m_strRemark));

        msgLog = QString(12,space)
                .append(QString("<%1").arg(strTarName))\
                .append(QString(fillBlankSpace(strTarName.length(),m_respTagLenMax),space))\
                .append(QString("Response=\"%1\"").arg(strResponse))\
                .append(QString(fillBlankSpace(strResponse.length(),m_respTagLenMax),space))\
                .append(QString(" value=\"$%1\"").arg(strValue))\
                .append(QString(QString(fillBlankSpace(strValue.length(),m_respTagLenMax),space)))
                .append(QString("remark =\"%1\"/>""").arg(m_FieldGatherList.at(k).m_strRemark));

        ui->textEditLog->append(msgLog);

    }
    msgLabel +=QString(8,space).append(QString("</Response>\r\n"));

    msgLog = QString(8,space).append(QString("</Response>"));
    ui->textEditLog->append(msgLog);

    msgLabel +=QString(4,space).append(QString("</Msg>\r\n"));

    msgLog = QString(4,space).append(QString("</Msg>"));
    ui->textEditLog->append(msgLog);
}
void Widget::AppendLabel(QString &filePath, QString &msgLabel,QString &findKey)
{
    //追加节点
    //读文件
    QFile rFile(filePath);
    rFile.encodeName("UTF-8");
    if(!rFile.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("文件打开失败"));
        return;
    }

    QString strContext;
    strContext = rFile.readAll();
    int pos = strContext.lastIndexOf(findKey);
    strContext.insert(pos-1,msgLabel);

    rFile.close();

    //写文件
    QFile wFile(filePath);
    wFile.encodeName("UTF-8");
    if(!wFile.open(QIODevice::WriteOnly))
    {
        return;
    }
    QTextStream stream(&wFile);
    stream.setCodec("UTF-8");
    stream.setGenerateByteOrderMark(true);
    stream << strContext;
    qDebug() << "strContext" << strContext;
    wFile.close();

}
void Widget::MapToPrepareDataDef(FieldMap &myFieldMap,QString &xml,int len)
{
    xml.clear();
    QChar space = QChar(' ');
    for(QMap<QString,QString>::iterator it= myFieldMap.begin(); it!= myFieldMap.end(); it++)
    {
        xml += QString(4,space).append(QString("<%1").arg(it.key()).append(QString(fillBlankSpace(it.key().length(),len),space))
                .append(QString(" value =\"\"   "))
                .append(QString("remark =\"%1\" /> \r\n").arg(it.value())));
    }
}
void Widget::DataTransformDefXML(QString &msgID,QString &tranCodeName,QString &filePath, int len)
{
    qDebug() << "Widget::DataTransformDefXML" ;
    if(msgID.isEmpty() || tranCodeName.isEmpty() || filePath.isEmpty())
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("请检查输入框数据"));
        return;
    }
    ui->textEditLog->append(filePath);

    QString strHead = QString("%1%2%3")
            .arg(QString("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"))
            .arg(QString("<Cols>\r\n"))
            .arg(QString("</Cols>"));

    QString key = QString("Cols");
    CreateXmlHeadAndBody(filePath,strHead,key);
    QString xml;
    MapToPrepareDataDef(m_FieldMap,xml,len);
    QString keyLabel = QString("</Cols>");
    qDebug() << "xml " << xml;
    AppendLabel(filePath,xml,keyLabel);

}
//生成Msg
void Widget::on_buttonTransMsg_clicked()
{
    qDebug() << "Def XML";
    QString AppID = ui->lineEditP2AppID->text().trimmed().toUtf8();
    QString msgID = ui->lineEditP2AppMsgID->text().trimmed().toUtf8();
    QString tranCodeName = ui->lineEditP2TransName->text().trimmed().toUtf8();
    QString targetFile = QString("%1/Msg/Msg_%2.xml").arg(m_tempDir).arg(AppID);

    if(AppID.isEmpty() || msgID.isEmpty() || tranCodeName.isEmpty())
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("输入框数据不能为空！"));
        return;
    }

    //先判断是否存在这个id
    //QString strMsgID = QString("%1_%2").arg(AppID).arg(msgID);
    bool isExist = DocumentAttributeExists(targetFile,msgID);
    if(isExist)
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("请不要重复插入节点"));
        return;
    }
    //读数据保存
    ReadFieldAndSaveToData(m_strChannelType);
    //写数据
    DataTransformMsgXML(msgID, tranCodeName, targetFile,m_strChannelType,AppID);

}

// page2 生成transDef
void Widget::on_buttonTransdef_clicked()
{
    //读取需要追加的文件
    ReadFieldAndSaveToData(m_strChannelType);
    QString AppID = toL8B(ui->lineEditP2AppID->text().trimmed().toStdString().data());
    QString msgID =ui->lineEditP2AppMsgID->text().trimmed();
    QString tranCodeName = ui->lineEditP2TransName->text().trimmed();
    QString fileName = QString("%1/DataPool/TranDataDef_%2.xml").arg(m_tempDir).arg(AppID);
    if(AppID.isEmpty()|| msgID.isEmpty() || tranCodeName.isEmpty())
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("输入框数据不能为空！"));
        return;
    }
    DataTransformDefXML(msgID, tranCodeName, fileName , m_TrandataDefLen);
    //去除重复的
    ClearTransDefRepeat(fileName);

}
//公共函数1
int Widget::fillBlankSpace(int arg1, int arg2)
{
    return (arg2 > arg1)?(arg2 - arg1):(arg1 - arg2);
}
//公共函数2
bool Widget::DocumentAttributeExists(QString &filePath,QString &MsgID)
{
    QFile file(filePath);
    if(!file.open(QIODevice::ReadWrite))
    {
       QMessageBox::critical(this,toL8B("错误"),toL8B("打开文件失败"));
       return false;
    }
    qDebug () << "enter";
    QDomDocument doc;
    bool isOk =doc.setContent(&file);
    file.close();
    if(!isOk)
    {
        CreateFileBodyXml(filePath);
        ui->textEditLog->append(toL8B("文件为空 新建%1").arg(filePath));
        return false;
    }

    QDomElement root = doc.documentElement();
    if(!root.isElement())
    {
        return false;
    }
    qDebug() << MsgID;
    QDomNodeList nList = root.childNodes();
    for (int i=0;i < nList.size(); i++)
    {
       QDomElement elem = nList.at(i).toElement();
       if(elem.attribute("id").indexOf(MsgID)>= 0)
       {
            ui->textEditLog->append(toL8B("文件中存在%1").arg(MsgID));
            return true;
       }
    }
    return false;
}
//生成test 网页
void Widget::on_buttonTest_clicked()
{
    m_CreateHtml->CreateTempJS();
    m_CreateHtml->CreateMainPageTest();
}
void Widget::on_ShowInitCreateHtmlLog(QString arg)
{
    if(arg == "CompleteJS")
    {
        ui->textEditLog->append(toL8B("Temp.js 转换完成"));
    }
    else if(arg == "CompleteHtml")
    {
        ui->textEditLog->append(toL8B("C:/csap/Nisp/html/MainPageTest.htm 已导入script\r\n"));
        ui->textEditLog->append("Runing  C:/csap/Nisp/html/MainPageTest.htm ");
    }
}


void Widget::ReadLabelAndRemarktoSaveDate(XMLFileList &Mylist,FieldMap &MyMap ,int &len)
{
    len =0;
    //去掉交易码
    Mylist.pop_front();
    for(int i =0; i < Mylist.size(); i++ )
    {
        QString strKey = Mylist.at(i).m_strValue.mid(1);
        QString strValue = Mylist.at(i).m_strRemark;
        int keyLen = strKey.length();
        int ValLen = strValue.length();
        len = compareThree(keyLen,ValLen,len);
        MyMap.insert(strKey,strValue);
    }
}

void Widget::ReadXmltoMap(const QString &strFilePath,TransDefMap &myMap,int &maxFeildLen)
{
    qDebug() << "Widget::ReadXmltoMap" ;
    QDomDocument doc;
    QFile file(strFilePath);
    file.encodeName("UTF-8");
    file.open(QIODevice::ReadOnly);
    maxFeildLen =0;
    if(!doc.setContent(&file))
    {
        //QMessageBox::critical(NULL, toL8B("错误"),toL8B("读取 %1 错误").arg(strFilePath));
    }
    file.close();
    QDomElement m_Root = doc.documentElement();
    if(!m_Root.hasChildNodes())
    {
        QMessageBox::critical(this, toL8B("错误"),toL8B("读取 %1 错误").arg(strFilePath));
        return;
    }
    QDomNode m_Node = m_Root.firstChild();
    m_xmlRootTag = m_Root.tagName();
    //容错
    if(m_Root.hasAttribute("remark"))
        m_xmlRootRemark = m_Root.attribute("remark");
    else if(m_Root.hasAttribute("Remark"))
        m_xmlRootRemark = m_Root.attribute("Remark");
    else
        m_xmlRootRemark = "";

    qDebug() << "m_xmlRootRemark " << m_xmlRootRemark ;

    m_RecordNum =0;
    TransDef_RV remarkValue;
    while(!m_Node.isNull())
    {
        QDomElement m_Elem = m_Node.toElement();
        if(m_Elem.isElement())
        {
            auto item = myMap.find(m_Elem.tagName());
            if(item != myMap.end() && item.key() == m_Elem.tagName())
            {
               m_repeatMap[item.key()] = m_repeatMap[item.key()] + 1;
               //ui->textEditLog->append(toL8B("键值重复 <font color=\"#FF0000\"> Key %1 remark %2 </font>").arg(item.key()).arg(item.value().m_remark));
            }
            else
            {
                m_repeatMap.insert(m_Elem.tagName(),1) ;
                //容错
                remarkValue.m_remark.clear();
                remarkValue.m_value.clear();
                if(m_Elem.hasAttribute("Remark"))
                {
                    remarkValue.m_remark =  m_Elem.attribute("Remark");
                }
                else if(m_Elem.hasAttribute("remark")){
                    remarkValue.m_remark = m_Elem.attribute("remark");
                }

                if(m_Elem.hasAttribute("Value"))
                {
                    remarkValue.m_value =  m_Elem.attribute("Value");
                }
                else if(m_Elem.hasAttribute("value")){
                    remarkValue.m_value = m_Elem.attribute("value");
                }

                myMap.insert(m_Elem.tagName(),remarkValue);
                qDebug() << m_Elem.tagName() << m_Elem.attribute("remark");
                ui->textEditLog->append(toL8B("插入数据 <font color=\"#FF0000\"> Key %1 remark %2 </font>").arg(m_Elem.tagName()).arg(remarkValue.m_remark));
                maxFeildLen = compareTwo(m_Elem.tagName().length(),maxFeildLen) ;
                qDebug () << "insert OK " << maxFeildLen;
            }
        }
        m_Node = m_Node.nextSibling();
    }

    ui->textEditLog->append(toL8B("-------------------重复键值------------------------"));
    for(auto repeatIt = m_repeatMap.begin(); repeatIt != m_repeatMap.end(); repeatIt++)
    {
        if(repeatIt.value() > 1)
        {
             ui->textEditLog->append(toL8B("<font color=\"#0000FF\"> Key %1 </font> 重复<font color=\"#00FF00\"> %2 </font> 次")
                     .arg(repeatIt.key())
                     .arg(repeatIt.value()));
        }
    }
    ui->textEditLog->append("-------------------------------------------");
    for(auto it =myMap.begin(); it != myMap.end(); it++)
    {
        m_RecordNum++;
        ui->textEditLog->append(toL8B("<font color=\"#0000FF\"> Key %1   remark %2</font>").arg(it.key()).arg(it.value().m_remark));
    }
    ui->textEditLog->append(toL8B(" 标签总数 <font color=\"#0000FF\"> %1 </font>").arg(m_RecordNum));
}
void Widget::mapFormatTransDefColsBody(TransDefMap &myMap, QString &strformat,int &maxFeildLen)
{
    strformat.clear();

    QChar space =QChar(' ');
    for(auto it = myMap.begin(); it != myMap.end();it++)
    {
       QString strKey = it.key();
//       int maxLen =0;
//       if(strKey.indexOf("RP")!=-1)
//       {
//           maxLen = maxFeildLen;
//       }
//       else{
//           maxLen = maxFeildLen + 4;
//       }
       qDebug() <<strKey.length()<< "  " << maxFeildLen +4 << " Spance " <<fillBlankSpace(strKey.length(),maxFeildLen +4);
       TransDef_RV ValRV = it.value();
       strformat += QString("%1<%2 %3  value =\"%4\" %5remark =\"%6\"/>\r\n")
               .arg(QString(4,space))
               .arg(strKey)
             .arg(QString(fillBlankSpace(strKey.length(),maxFeildLen +4),space))
             .arg(ValRV.m_value)
             .arg(QString(fillBlankSpace(ValRV.m_value.length(),maxFeildLen +4),space))
             .arg(ValRV.m_remark);
    }

}
void Widget::WriteTransDefXml(QString &strFilePath, TransDefMap &myMap,int &maxFeildLen)
{
    qDebug() << QString("Widget::Write %1 Xml").arg(m_xmlRootTag) ;
    //重新生成文件创建文件头

    QString strColsBody;
    mapFormatTransDefColsBody(myMap,strColsBody,maxFeildLen);
    qDebug() << "m_xmlRootTag "  << m_xmlRootTag;
    QString keyLabel = QString("</%1>").arg(m_xmlRootTag);
    QString rootTagContent ="";
    if(!m_xmlRootRemark.isEmpty())
    {
        rootTagContent = QString("%1 remark =\"%2\"").arg(m_xmlRootTag).arg(m_xmlRootRemark.toStdString().data());
    }
    else
    {
        rootTagContent = m_xmlRootTag;
    }
    QString strHead = QString("%1<%2>\r\n</%3>")
            .arg("<?xml version=\"1.0\" encoding=\"utf-8\"?> \r\n")
            .arg(rootTagContent)
            .arg(m_xmlRootTag);

    qDebug()  <<"strHead "<< strHead << " keyLabel " <<keyLabel;
    insertXmlContext(strFilePath, strHead, strColsBody, keyLabel);
}
void Widget::insertXmlContext(QString &filePath,QString &xmlHead, QString &text, QString &findKey)
{
    QString xml;
    xml.clear();
    QFile iFile(filePath);
    if(!iFile.open(QIODevice::WriteOnly))
    {
        return;
    }
    qint64 pos = xmlHead.indexOf(findKey);
    qDebug() << "pos " << pos;
    if(pos >=0 )
    {
        xml = xmlHead.insert(pos-1,text);
        QTextStream iStream(&iFile);
        iStream.setCodec("UTF-8");
        iStream.setGenerateByteOrderMark(true);
        iStream << xml;
        qDebug() << "xml " << xml;
    }
    iFile.close();
}
//生成msg
void Widget::on_buttonMsg_clicked()
{

    m_msgID.clear();
    m_AppID.clear();
    m_MAC.clear();


    m_msgID = ui->lineEditMsgID->text().trimmed();
    m_AppID = ui->lineEditAppID->text().trimmed();
    m_MAC =ui->lineEditMac->text().trimmed();
    QString msgName = ui->lineEditName->text().trimmed();
    QString filePath = ui->lineEditSourcePath->text().trimmed();
    //QString newFilePath = ui->lineEditTargetPath->text().trimmed();
    QString newFilePath = QString("%1/Msg/Msg_%2.xml").arg(m_tempDir).arg(m_AppID);


#ifdef QT_DEBUG
    m_msgID = QString("99NISPLC0020");
    m_AppID = QString("E59906");
    m_MAC = QString("true");
    msgName = toL8B("理财购买");
    filePath = QString("D:/ABC/ABC_SuperTeller/Src/B05_FINANCE/Conf/Msg/Msg_B05_finance.xml");
#endif

    if(!filePath.isEmpty() && !newFilePath.isEmpty() && !m_msgID.isEmpty())
    {
        ReadMsg(filePath, m_msgID, m_AppID);

#ifdef QT_DEBUG
        for (int i=0; i < m_XMLList.size(); i++)
        {
            qDebug() << m_XMLList.at(i).m_strFlag;
            qDebug() << m_XMLList.at(i).m_strRemark;
            qDebug() << m_XMLList.at(i).m_strRequestPath;
            qDebug() << m_XMLList.at(i).m_strResponsePath;
            qDebug() << m_XMLList.at(i).m_strValue;

        }
#endif
        createXML(newFilePath);
        appendXML(newFilePath, m_XMLList, m_msgID, msgName, m_MAC);

    }
    else
    {
        QMessageBox::information(this,toL8B("提示"),toL8B("请检查输入框数据"));
        return;
    }

}
//page 1 生成TransDef
void Widget::on_buttonTransDef_clicked()
{
    m_AppID = ui->lineEditAppID->text().trimmed().toUtf8();
    m_msgID = ui->lineEditMsgID->text().trimmed().toUtf8();
    QString tranCodeName = ui->lineEditName->text().trimmed().toUtf8();
    QString targetFile = QString("%1/DataPool/TranDataDef_%2.xml").arg(m_tempDir).arg(m_AppID);
    QString fileSourcePath = ui->lineEditSourcePath->text().trimmed();
    if(m_AppID.isEmpty() || m_msgID.isEmpty() || tranCodeName.isEmpty() || fileSourcePath.isEmpty())
    {
        QMessageBox::information(this,toL8B("提示"),toL8B("请检查输入框数据"));
        return;
    }
    ReadMsg(fileSourcePath, m_msgID, m_AppID);
    m_FieldMap.clear();
    m_TrandataDefLen =0;
    ReadLabelAndRemarktoSaveDate(m_XMLList,m_FieldMap,m_TrandataDefLen);
    DataTransformDefXML(m_msgID, tranCodeName, targetFile ,m_TrandataDefLen);
    ClearTransDefRepeat(targetFile);
}


void Widget::ClearTransDefRepeat(QString &filePath)
{
    qDebug() << "Widget::ClearTransDefRepeat" ;
    m_dataMap.clear();
    m_repeatMap.clear();
    m_TransDefFeildLen =0;
    //读文件
    ReadXmltoMap(filePath,m_dataMap,m_TransDefFeildLen);
    //写文件
    WriteTransDefXml(filePath,m_dataMap,m_TransDefFeildLen);
}
//一键去重
void Widget::on_buttonClearRepeat_clicked()
{
    //设置文件路径
    QString filePath = ui->lineEditRepeat->text();
    if(filePath.isEmpty())
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("请选择文件或输入文件路径"));
        return;
    }
    //先备份文件
    QFileInfo fileInfo(filePath);
    //qDebug() << fileInfo.path() << fileInfo.baseName() ;
    QString sourceFileName = fileInfo.baseName().append("_bak.").append(fileInfo.suffix());
    QString destFilPath = fileInfo.path().append("\\").append(sourceFileName);
    QFile destFile(destFilPath);
    if(destFile.exists())
    {
        //如果存在就删除
        destFile.remove();
    }
    destFile.close();
    bool isOk = QFile::copy(filePath,destFilPath);
    if(!isOk)
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("文件备份失败"));
    }
    ClearTransDefRepeat(filePath);
}

void Widget::on_comboxChannelType_currentIndexChanged(const QString &arg1)
{

    if(arg1 == toL8B("自助服务终端"))
    {
        m_strChannelType = QString("SST");

    }
    else if(arg1 == toL8B("超级柜台"))
    {
        m_strChannelType = QString("SuperTeller");
    }
    initPage2Placeholder(m_strChannelType);
}

 //编辑工具
void Widget::on_comboBoxEdit_currentIndexChanged(int index)
{
    qDebug() << index;
    SetIDEPath(index);
}
void Widget::SetIDEPath(int index){
    QString appStartPath( QApplication::applicationDirPath());
    QString IDENameList,IDEName;
    QString formatMsgPath = QString("%1/%2").arg(appStartPath).arg("formatMsg.ini");
    QSettings setterIni(formatMsgPath, QSettings::IniFormat);
    setterIni.setIniCodec("UTF-8");
    IDENameList = setterIni.value("IDE/IDEName").toString();
    qDebug() <<IDENameList;
    if(IDENameList.isEmpty()){
        m_OpenOtherEdit = "notepad++";
        m_OpenEditOtherName = "notepad++";
        return;
    }

    QStringList itemsIDE = IDENameList.split("|",QString::SkipEmptyParts);
    if(itemsIDE.count() >= index){
        IDEName = itemsIDE.at(index);
        m_OpenOtherEdit = IDEName;
        m_OpenEditOtherName = IDEName;
        return;
    }
    else {
        m_OpenOtherEdit = "notepad++";
        m_OpenEditOtherName = "notepad++";
        return;
    }


}

void Widget::on_CheckBtn_clicked()
{
    QString msgPath = ui->lineEditRepeat->text().trimmed().toUtf8();
    QFile file(msgPath);
    if(!file.exists())
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("文件%1不存在").arg(filePath));
        return;
    }
    file.encodeName("UTF-8");
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("文件打开失败"));
        return;
    }
    QDomDocument doc;
    if(!doc.setContent(&file))
    {
        QMessageBox::critical(this,toL8B("错误"),toL8B("文档 setContent 失败"));
        file.close();
        return;
    }
    file.close();
    //获取根元素
    QDomElement root =doc.documentElement();
    if(!root.hasChildNodes())
    {
        return;
    }

}
